package top.yueyazhui.learn_shiro_spring_boot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yueyazhui.learn_shiro_spring_boot.model.Response;

import java.util.List;

/**
 * @Author yueyazhui
 * @Date 2023/2/18
 */
@RestController
public class LoginController {

    @PostMapping("login")
    public Response login(String username, String password) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        // 开启 RememberMe
        usernamePasswordToken.setRememberMe(true);
        try {
            // 执行登录
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            List list = subject.getPrincipals().asList();
            for (Object o : list) {
                System.out.println("o = " + o);
            }
        } catch (AuthenticationException e) {
            return Response.error("登录失败", e.getMessage());
        }
        return Response.success("登录成功");
    }

    @GetMapping("logout")
    public Response logout() {
        try {
            SecurityUtils.getSubject().logout();
            return Response.success("注销成功");
        } catch (Exception e) {
            return Response.error("注销失败");
        }
    }
}
